package com.example.fw;

import java.util.List;

import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;

import com.example.tests.ContactData;
import com.example.utils.SortedListOf;

public class ContactHelper extends HelperBase {

	public ContactHelper(ApplicationManager manager) {
		super(manager);
	}

	public ContactHelper createContact(ContactData contact) {
		manager.navigatiTo().mainPage();
		addNewContact();
		fillContactForm(contact);
		submitAddNew();
		manager.navigatiTo().mainPage();
		rebuildCache();
		return this;
	}

	public ContactHelper deletecontact(int index) {
		manager.navigatiTo().mainPage();
		manager.getContactHelper().editConact(index);
		manager.getContactHelper().delContact();
		manager.navigatiTo().mainPage();
		rebuildCache();
		return this;
	}
	
	// --------------------------------

	private void rebuildCache() {
		cachedContacts = new SortedListOf<ContactData>();
		// manager.navigatiTo().mainPage();
		List<WebElement> checkboxes = driver
				.findElements(By.name("selected[]"));
		for (WebElement checkbox : checkboxes) {
			String title = checkbox.getAttribute("title");
			String name = title.substring("Select (".length(), title.length()
					- ")".length());
			cachedContacts.add(new ContactData(name));
		}
	}

	private SortedListOf<ContactData> cachedContacts;

	public SortedListOf<ContactData> getContacts() {
		if (cachedContacts == null) {
			rebuildCache();
		}
		return cachedContacts;
	}

	public void addNewContact() {
		click(By.xpath("//div//div[3]//ul//li[2]/a"));
	}

	public void submitAddNew() {
		click(By.name("submit"));
	}

	public void fillContactForm(ContactData contact) {
		type(By.name("firstname"), contact.firstname);
		type(By.name("lastname"), contact.lastname);
		type(By.name("address"), contact.address1);
		type(By.name("home"), contact.hphone);
		type(By.name("mobile"), contact.mphone);
		type(By.name("work"), contact.wphone);
		type(By.name("email"), contact.email1);
		type(By.name("email2"), contact.email2);
		selectByText(By.name("bday"), contact.bday);
		selectByText(By.name("bmonth"), contact.bmonth);
		selectByText(By.name("new_group"), contact.group);
		type(By.name("address2"), contact.address2);
		type(By.name("phone2"), contact.phone2);

	}

	public void editConact(int index) {
		selectContactByIndex(index);
		click(By.xpath("//div//div[4]//form[2]/table/tbody//tr[" + (index + 1) + "]//td[7]/a/img"));
	}

	private void selectContactByIndex(int index) {
		click(By.xpath("//input[@name='selected[]'][" + (index + 1) + "]"));

	}

	public void submitModifContact() {
		click(By.name("update"));
	}

	public void delContact() {
		click(By.xpath("//div//div[4]//form[2]/input[2]"));

	}

}